package com.lsa.helpers.tree.binary;

import java.util.ArrayList;
import java.util.List;

import com.lsa.helpers.tree.ITreeNode;

/**
 * @author lsa
 *
 * @param <T>
 */
public class BinaryTreeNode<T> implements IBinaryTreeNode<T> {
	
	private T data;
	
	private IBinaryTreeNode<T> leftChild;
	private IBinaryTreeNode<T> rightChild;
	
	public BinaryTreeNode(T data) {
		this.data = data;
	}

	@Override
	public T getData() {
		return data;
	}

	@Override
	public void setData(T data) {
		this.data = data;
	}

	@Override
	public List<ITreeNode<T>> getChildren() {
		List<ITreeNode<T>> children = new ArrayList<ITreeNode<T>>();
		for (IBinaryTreeNode<T> child : new IBinaryTreeNode []{leftChild, rightChild}) {
			if (child != null) children.add(child);
		}
		return children;
	}

	public void addChild(ITreeNode<T> child) {
		if (!(child instanceof IBinaryTreeNode<?>)){
			throw new IllegalArgumentException();
		}
		if (leftChild == null){
			leftChild = (IBinaryTreeNode<T>)child;
		}
		else if (rightChild == null){
			rightChild = (IBinaryTreeNode<T>)child;
		}
		throw new RuntimeException("Binary tree node cannot have more than 2 childs");
	}

	@Override
	public IBinaryTreeNode<T> getLeftSubtree() {
		return leftChild;
	}

	@Override
	public IBinaryTreeNode<T> getRightSubtree() {
		return rightChild;
	}

	@Override
	public void setLeftSubtree(IBinaryTreeNode<T> subtree) {
		this.leftChild = subtree;
	}

	@Override
	public void setRightSubtree(IBinaryTreeNode<T> subtree) {
		this.rightChild = subtree;
	}

	@Override
	public String toString() {
		return "TreeNode [data=" + data + "]";
	}
}
